package com.zsc.oj.job.once.schedul;

import com.zsc.oj.mapper.QuestionEsDao;
import com.zsc.oj.mapper.QuestionMapper;
import com.zsc.oj.model.dto.question.QuestionEsDTO;
import com.zsc.oj.model.entity.Question;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SyncQuestionToEs {

    @Resource
    private QuestionEsDao questionEsDao;

    @Resource
    private QuestionMapper questionMapper;

    @Scheduled(fixedRate = 60 * 1000) //1分钟
    public void syncQuestionToEs(){
        //MySQL查询近5分钟的数据
        long FIVE_MINUTE = 5 * 60 * 1000L;
        //过去的五分钟
        Date date = new Date(new Date().getTime() - FIVE_MINUTE);
        List<Question> questionList = questionMapper.listQuestionWithDelete(date);

        //将题目对象转成ES实体类
        List<QuestionEsDTO> questionEsDTOList = questionList.stream().map(QuestionEsDTO::objToDto).collect(Collectors.toList());

        //分页插入（ES的插入是根据索引下标进行插入的）
        int pageSize = 500;
        int size = questionEsDTOList.size();
        for (int i = 0; i < size; i += pageSize) {
            //同步数据下标不能超过总数量
            int end = Math.min(i+pageSize,size);
            //进行批量插入
            questionEsDao.saveAll(questionEsDTOList.subList(i,end));
        }
        log.info("sync question to es total {}",size);
    }
}
